package com.yjr.gulimall.ware.service.impl;

import com.yjr.common.constant.WareConstant;
import com.yjr.common.utils.R;
import com.yjr.gulimall.ware.entity.PurchaseDetailEntity;
import com.yjr.gulimall.ware.service.PurchaseDetailService;
import com.yjr.gulimall.ware.service.WareSkuService;
import com.yjr.gulimall.ware.vo.MergeVo;
import com.yjr.gulimall.ware.vo.PurchaseDoneVo;
import com.yjr.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjr.common.utils.PageUtils;
import com.yjr.common.utils.Query;

import com.yjr.gulimall.ware.dao.PurchaseDao;
import com.yjr.gulimall.ware.entity.PurchaseEntity;
import com.yjr.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> purchaseEntityQueryWrapper = new QueryWrapper<>();
        purchaseEntityQueryWrapper.eq("status",0).or().eq("status",1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                purchaseEntityQueryWrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {

        //如果采购单Id为空的话，那么就重新创建一个采购单
        Long purchaseId = mergeVo.getPurchaseId();
        if(purchaseId==null){
            PurchaseEntity purchaseEntity=new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntities = items.stream().map(a -> {

            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(a);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(purchaseDetailEntities);
    }

    @Override
    public void received(List<Long> ids) {
        if(CollectionUtils.isEmpty(ids)){
            return;
        }

        List<PurchaseEntity> purchaseEntities = ids.stream().map(this::getById).filter(item -> item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode() || item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode())
                .map(item -> {
                    item.setUpdateTime(new Date());
                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    return item;
                }).collect(Collectors.toList());

        this.updateBatchById(purchaseEntities);


        //改变采购项的状态
      purchaseEntities.stream().forEach(purchaseEntity -> {
          List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listDetailByPurchaseId(purchaseEntity.getId());
          List<PurchaseDetailEntity> entities = purchaseDetailEntities.stream().map(purchaseDetailEntity -> {
              PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
              detailEntity.setId(purchaseDetailEntity.getId());
              detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
              return detailEntity;
          }).collect(Collectors.toList());

          purchaseDetailService.updateBatchById(entities);

      });






    }
    @Transactional
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {

        //改变采购单的状态
        Long purchaseId = purchaseDoneVo.getId();
        Boolean flag=true;//是否有采购异常的单
        List<PurchaseDetailEntity> updates=new ArrayList<>();
        List<PurchaseItemDoneVo> purchaseDoneVoItems = purchaseDoneVo.getItems(); //采购项
        //改变采购项的状态
        for (PurchaseItemDoneVo purchaseDoneVoItem : purchaseDoneVoItems) {
            PurchaseDetailEntity purchaseDetailEntity=new PurchaseDetailEntity();
            if(purchaseDoneVoItem.getStatus()==WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                flag = false;
                purchaseDetailEntity.setStatus(purchaseDoneVoItem.getStatus());
            }
            else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //将成功采购的入库
                // 查出当前采购项的详细信息
                PurchaseDetailEntity entity = purchaseDetailService.getById(purchaseDoneVoItem.getItemId());
                // skuId、到那个仓库、sku名字
              wareSkuService.addStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum());
            }
            purchaseDetailEntity.setId(purchaseDoneVoItem.getItemId());

            updates.add(purchaseDetailEntity);
        }

        purchaseDetailService.updateBatchById(updates);

        PurchaseEntity purchaseEntity=new PurchaseEntity();
        purchaseEntity.setId(purchaseId);

      if(flag){
          purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
      }else {
          purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
      }

      purchaseEntity.setUpdateTime(new Date());
      this.updateById(purchaseEntity);


    }

}